15. Relational Operators

Relational Operators

Equality and Relational Operators

We’ve used some symbols like < => and == in our examples. These are known as Equality and Relational Operators. These operators work a lot like the math or arithmetic operators we’re used to (+ - / *). Arithmetic operators take two numbers and evaluate to another number. For example 5 + 3 evaluates to 8.

Equality and Relational Operators take two values (these are usually but not always numbers) and compare the values. They then evaluate to a boolean. They look like symbols that you might have used in math class to talk about comparing numbers.

The Equality and Relational Operators in Java

  • ==   Equal to (note that it is not a single = sign because this is the assignment operator)
  • !=    Not equal to
  • >     Greater than
  • >=   Greater than or equal to
  • <      Less than
  • <=    Less than or equal to

Example

Here's an example of how expressions using relational operators work:

5 < 10 is an expression meaning 5 is less than 10. This evaluates to the value true, because 5 is less than 10.

5 == 5 evaluates to true.

5 != 5 evaluates to false. This is because it is false that five is not equal to five.

Much more could be said about relational and equality operators. There is a lot of good information out on the web about these concepts. A good place to start is the Oracle Java tutorial about operators and Java basic operators.